package com.van.filter;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * Servlet Filter implementation class FilterDemo
 */
@WebFilter("/*")
public class FilterDemo implements Filter {
	private FilterConfig config;
	public static int pg ;
	public static int uv;
	public ArrayList<String> list = new ArrayList<String>();
    /**
     * Default constructor. 
     */
    public FilterDemo() {
       
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		pg++;
		HttpServletRequest r = (HttpServletRequest)request;
		HttpSession session = r.getSession();
		if(!list.contains(session.getId())){
			String sessionId = session.getId();
			list.add(sessionId);
			uv++;
		}
		
		ServletContext context = this.config.getServletContext();
		context.setAttribute("pageview", pg);
		context.setAttribute("uv", uv);
		context.setAttribute("sessionList", list);
		// pass the request along the filter chain
		chain.doFilter(request, response);
		
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
	}

}
